<template>
  <a-modal
    title="编辑机构"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="formLoading">
      <a-form :form="form">
        <a-form-item style="display: none;" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-input v-decorator="['id']" />
        </a-form-item>

        <a-form-item label="机构名称" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-input
            placeholder="请输入机构名称"
            v-decorator="['name', { rules: [{ required: true, message: '请输入机构名称！' }] }]"
          />
        </a-form-item>

        <!--        <a-form-item label="唯一编码" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>-->
        <!--          <a-input-->
        <!--            placeholder="请输入唯一编码"-->
        <!--            v-decorator="['code', { rules: [{ required: true, message: '请输入唯一编码！' }] }]"-->
        <!--          />-->
        <!--        </a-form-item>-->

        <a-form-item label="上级机构" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-tree-select
            v-decorator="['pid', { rules: [{ required: true, message: '请选择上级机构！' }] }]"
            style="width: 100%"
            :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
            :treeData="orgTree"
            placeholder="请选择上级机构"
            treeDefaultExpandAll
          >
            <span slot="title" slot-scope="{ id }">{{ id }} </span>
          </a-tree-select>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="排序">
          <a-input-number
            placeholder="请输入排序"
            style="width: 100%"
            v-decorator="['sort', { initialValue: 100 }]"
            :min="1"
            :max="1000"
          />
        </a-form-item>

        <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
          <a-textarea :rows="4" placeholder="请输入备注" v-decorator="['remark']"></a-textarea>
        </a-form-item>
        <!--        <a-form-item-->
        <!--          label="是否是网点"-->
        <!--          :labelCol="labelCol"-->
        <!--          :wrapperCol="wrapperCol"-->
        <!--        >-->
        <!--          <a-switch id="visible" checkedChildren="是" unCheckedChildren="否" v-model:checked="isSite" />&lt;!&ndash; defaultChecked &ndash;&gt;-->
        <!--        </a-form-item>-->
      </a-form>
      <el-form size="mini" inline label-position="right" label-width="180px" ref="form" :model="siteAdmin" v-if="false">
        <el-row>
          <el-col :span="12">
            <el-form-item label="网点名称：" prop="name" :rules="[{ required: true, message: '请输入' }]">
              <el-input v-model="siteAdmin.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址：" prop="address" :rules="[{ required: true, message: '请输入' }]">
              <el-input v-model="siteAdmin.address" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在城市：" prop="regionCode" :rules="[{ required: true, message: '请输入' }]">
              <ad-city-select v-model="siteAdmin.regionCode" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务城市：" prop="chargeCodeList" :rules="[{ required: true, message: '请输入' }]">
              <ad-city-multi-select
                v-model="siteAdmin.chargeCodeList"
                :cityData="cityData"
                :rules="[{ required: true, message: '请输入' }]"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择角色：" prop="roleId">
              <el-select v-model="roleId" placeholder="请选择">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { sysOrgEdit, getOrgTree } from '@/api/modular/system/orgManage'
import adTable from '@/mixins/adTable/index'
import adder from '@/views/system/site/add.vue'
import { getLevelList } from '@/api/city/provinceCity'
import AdInputNumber from '@/components/AdInputNumber'
import AdCitySelect from '@/components/AdCitySelect'
import AdCityMultiSelect from '@/components/AdCityMultiSelect'
import { getRolePage } from '@/api/modular/system/roleManage'
export default {
  components: { AdInputNumber, AdCitySelect, AdCityMultiSelect, adder },
  mixins: [adTable('order')],
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 15 }
      },
      orgTree: [],
      visible: false,
      confirmLoading: false,
      formLoading: true,
      form: this.$form.createForm(this),
      isSite: false,
      siteAdmin: {},
      cityData: [],
      roleOptions: [],
      roleId: ''
    }
  },
  created() {
    getLevelList().then(res => (this.cityData = res.data))
    getRolePage({ pageNo: 1, pageSize: 999 }).then(res => (this.roleOptions = res.data.rows))
  },
  methods: {
    // 初始化方法
    edit(record) {
      this.visible = true
      this.isSite = record.isSite === 2 ? true : false
      this.siteAdmin = record.siteAdmin ?? {}
      this.roleId = record.roleId
      this.getOrgTree()
      setTimeout(() => {
        this.form.setFieldsValue({
          id: record.id,
          name: record.name,
          code: record.code,
          sort: record.sort,
          pid: record.pid,
          remark: record.remark
        })
      }, 100)
    },

    /**
     * 获取机构树，并加载于表单中
     */
    getOrgTree() {
      getOrgTree().then(res => {
        this.formLoading = false
        if (!res.success) {
          this.orgTree = []
          return
        }
        this.orgTree = [
          {
            id: '-1',
            parentId: '0',
            title: '顶级',
            value: '0',
            pid: '0',
            children: res.data
          }
        ]
      })
    },
    check(values) {
      if (this.isSite) {
        if (!this.siteAdmin.name) {
          this.$message.error('请填写网点名称')
          this.confirmLoading = false
          return
        }
        if (!this.siteAdmin.address) {
          this.$message.error('请填写网点地址')
          this.confirmLoading = false
          return
        }
        if (!this.siteAdmin.regionCode) {
          this.$message.error('请填写网点所在城市')
          this.confirmLoading = false
          return
        }
        if (!this.siteAdmin.chargeCodeList) {
          this.$message.error('请填写网点服务城市')
          this.confirmLoading = false
          return
        }
        values.siteAdmin = this.siteAdmin
        values.roleId = this.roleId
        values.isSite = 2
        this.getOrgEdit(values)
      } else {
        this.siteAdmin = {}
        values.siteAdmin = {}
        values.roleId = this.roleId
        values.isSite = 1
        this.getOrgEdit(values)
      }
    },
    getOrgEdit(values) {
      sysOrgEdit(values)
        .then(res => {
          if (res.success) {
            this.$message.success('编辑成功')
            this.visible = false
            this.confirmLoading = false
            this.$emit('ok', values)
            this.form.resetFields()
          } else {
            this.$message.error('编辑失败：' + res.message)
          }
        })
        .finally(res => {
          this.confirmLoading = false
        })
    },
    handleSubmit() {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true
      validateFields((errors, values) => {
        if (!errors) {
          this.check(values)
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.form.resetFields()
      this.visible = false
    }
  }
}
</script>
